<template>
  <el-dialog v-if="openForm" v-model="openBoole" :close-on-click-modal="false" :title="title" custom-class="mydialog"
             width="50%" @close="close">
    <el-form ref="openRef" :model="openForm" :rules="rules" label-width="120px" size="small">
      <el-row gutter="40">
        <el-col :span="24">
          <item-title title="基本信息"/>
        </el-col>
        <el-col :span="12">
          <el-form-item label="兼职人员姓名" prop="userName">
            <el-input v-model="openForm.userName" clearable placeholder="请输入兼职人员姓名"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="openForm.sex">
              <el-radio label="1">男</el-radio>
              <el-radio label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="tel">
            <el-input v-model="openForm.tel" clearable placeholder="请输入联系电话"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证" prop="cardNumber">
            <el-input v-model="openForm.cardNumber" clearable placeholder="请输入身份证号码"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="openForm.address" clearable placeholder="请输入详细地址"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="身份证附件" prop="cardFiles">
            <div class="qualityFiles-container">
              <div v-for="(item,index) in openForm.cardFiles" :key="index" class="file-item">
                <image-upload-view ref="imageUploadView" :data="item"/>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer" style="display:flex;justify-content:center;align-items:center;">
        <el-button class="border-btn" size="small" style="margin-right: 20px;" @click="close">取消</el-button>
        <el-button class="main-btn" size="small" type="primary" @click="handlSubmit">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {getCurrentInstance, inject, onMounted, reactive, ref, toRefs,} from "vue";
import {validateVEIdCard, validateVETel} from "@/utils/validate";
import {crmStore} from "@CRM/store";

export default {
  name: "FormPersonnel",
  props: {
    agentType: {
      type: String,
      default: "",
    },
  },
  setup(props, context) {
    //* ************自定义效验**********
    const validateTel = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("手机号不能为空"));
      } else {
        if (validateVETel(value)) {
          callback(new Error("手机号格式不正确"));
        } else {
          callback();
        }
      }
    };

    const validateCardFiles = (rule, value, callback) => {
      if (data.openForm.cardFiles.length === 0) {
        callback(new Error("请上传身份证"));
      } else {
        for (let i = 0; i < data.openForm.cardFiles.length; i++) {
          const a = data.openForm.cardFiles[i];
          if (a.url === "") {
            callback(new Error("请上传身份证"));
          } else {
            callback();
          }
        }
      }
    };

    const validateIdCard = (rule, value, callback) => {
      if (value === "" || value === null) {
        callback();
      } else {
        if (validateVEIdCard(value)) {
          callback(new Error("格式不正确"));
        } else {
          callback();
        }
      }
    };
    //* ********************************
    const api = inject("api");
    const currentInstance = getCurrentInstance();
    var data = reactive({
      openBoole: false,
      openForm: {
        userName: "",
        tel: "",
        sex: "1",
        cardNumber: "",
        address: "",
        cardFiles:
            JSON.parse(
                JSON.stringify(
                    crmStore.getters["jsonData/getJsonData"][
                        "part_person_qualification"
                        ].data
                )
            ) || [],
        agentType: props.agentType,
      },
      openRef: null,
      title: "新建兼职人员",
      rules: {
        userName: [
          {required: true, message: "请输入兼职人员", trigger: "blur"},
        ],

        cardNumber: [{validator: validateIdCard, trigger: "blur"}],
        tel: [{required: true, validator: validateTel, trigger: "blur"}],
        // cardFiles: [
        //   { validator: validateCardFiles, trigger: 'blur'},
        // ],
      },
      agentPersonLevel:
          crmStore.getters["dictionary/getDictionary"]["agent_person_level"],
      imageUploadView: null,
      strNum: null,
    });

    const close = () => {
      data.openBoole = false;
      handlRemove();
    };

    const handlRemove = () => {
      data.openRef.clearValidate();
      data.openRef.resetFields();
    };

    const open = (val, num, strNum) => {
      data.openForm = {
        agentLevel: "", // 代理级别
        userName: "",
        tel: "",
        sex: "1",
        cardNumber: "",
        address: "",
        cardFiles:
            JSON.parse(
                JSON.stringify(
                    crmStore.getters["jsonData/getJsonData"][
                        "part_person_qualification"
                        ].data
                )
            ) || [],
        agentType: props.agentType,
      };
      if (num === 1) {
        data.title = "新建兼职人员";
      }
      if (num === 2) {
        data.title = "变更兼职人员";
      }
      if (num === 3) {
        data.title = "兼职人员确认";
      }
      if (val) {
        handlDetail(val);
      }
      if (strNum) {
        data.strNum = strNum;
        if (data.strNum === 2) {
          data.title = "编辑兼职人员";
        }
      }

      data.openBoole = true;
    };

    const handlSubmit = () => {
      data.openRef.validate((valid) => {
        if (valid) {
          const commit = ref(undefined);
          const msgs = ref("");
          if (data.openForm.id) {
            if (data.strNum === 1) {
              commit.value = api.channelAgent.POTENTIALAGENT_CHANGE;
              msgs.value = "变更成功";
            }
            if (data.strNum === 2) {
              commit.value = api.channelAgent.POTENTIALAGENT_UPDATE;
              msgs.value = "编辑成功";
            }
            if (data.strNum === 3) {
              commit.value = api.editorial.EDITORIAL_CUSTOMER_ENTERPRISE_UPDATE;
              msgs.value = "确认成功";
            }
          } else {
            commit.value = api.channelAgent.POTENTIALAGENT_CREATE;
            msgs.value = "创建成功";
          }
          commit.value(data.openForm).then((res) => {
            if (res.code === 0) {
              currentInstance.proxy.customMessage({
                type: "success",
                message: msgs.value,
              });
              context.emit("succsess");
              close();
            } else {
              currentInstance.proxy.customMessage({
                type: "error",
                message: res.msg,
              });
            }
          });
        }
      });
    };

    const handlDetail = async (id) => {
      const res = await api.channelAgent.POTENTIALAGENT_DETAIL(id);
      if (res.code === 0) {
        const dataAgent = reactive(res.data.data);
        for (const key in data.openForm) {
          data.openForm[key] = dataAgent[key];
        }
        data.openForm.id = dataAgent.id;
      }
    };

    onMounted((_) => {
    });

    return {
      ...toRefs(data),
      close,
      open,
      handlSubmit,
      handlRemove,
      handlDetail,
    };
  },
};
</script>

<style lang="scss" scoped>
</style>
